import platform
import socket
import uuid

class NetUtil:

    @staticmethod
    def subnet_to_cidr(subnet_mask : str):
        """将子网掩码转换为CIDR格式"""
        try:
            parts = subnet_mask.split('.')
            binary_str = ''.join(format(int(part), '08b') for part in parts)
            return binary_str.count('1')
        except Exception:
            # 默认返回24 (/24 = 255.255.255.0)
            return 24
        
    @staticmethod
    def __set_windows_static_ip(interface_name : str, ip : str, subnet_mask : str, gateway : str):
        """在Windows上设置静态IP"""
        import subprocess
        
        cmd = f'netsh interface ip set address name="{interface_name}" static {ip} {subnet_mask}'
        if gateway != "":
            cmd += f' {gateway}'
        try:
            print(f"执行命令: {cmd}")
            subprocess.check_call(cmd, shell=True)
            return True, None
        except subprocess.CalledProcessError as e:
            return False, f"修改网卡信息错误: {e}"
        except Exception as e:
            return False, f"出现了未知错误: {e}"

    @staticmethod
    def __set_linux_static_ip(interface_name: str, ip: str, subnet_mask: str, gateway: str):
        """在Linux上设置静态IP"""
        import subprocess
        try:
            # 计算CIDR
            cidr = NetUtil.subnet_to_cidr(subnet_mask)
            
            ip_cmd = f'netplan set ethernets.{interface_name}.addresses=["{ip}/{cidr}"]'
            subprocess.check_call(ip_cmd, shell=True)
            print(f"执行命令: {ip_cmd}")
            
            if gateway:
                gw_cmd = f'netplan set ethernets.{interface_name}.gateway4={gateway}'
                subprocess.check_call(gw_cmd, shell=True)
                print(f"执行命令: {gw_cmd}")
            
            exec_cmd = "netplan apply"
            subprocess.check_call(exec_cmd, shell=True)
            print(f"执行命令: {exec_cmd}")
            return True, None
        except subprocess.CalledProcessError as e:
            return False, f"修改网卡信息错误: {e}"
        except Exception as e:
            return False, f"出现了未知错误: {e}"

    @staticmethod
    def set_static_ip(interface_name : str, ip : str, subnet_mask : str, gateway : str):
        """设置静态IP"""
        if not interface_name:
            return False, "interface_name 不能为空"
        if not ip:
            return False, "ip 不能为空"
        if not subnet_mask:
            return False, "subnet_mask 不能为空"
        
        if platform.system() == 'Windows':
            return NetUtil.__set_windows_static_ip(interface_name, ip, subnet_mask, gateway)
        elif platform.system() == 'Linux':
            return NetUtil.__set_linux_static_ip(interface_name, ip, subnet_mask, gateway)
        else:
            return False, "不支持的平台"

    @staticmethod
    def get_network_interfaces():
        """获取网络接口列表"""
        try:
            import psutil
            interfaces = list()
            
            # 获取IP和子网掩码
            for iface in psutil.net_if_addrs().items():
                interfaces.append(iface[0])
            
            return True, interfaces
        except ImportError:
            return False
        except Exception as e:
            return False
   
    @staticmethod    
    def get_network_info_ipv4(interface_name : str):
        """获取当前网络接口的IP、子网掩码和网关"""
        if not interface_name:
            return False
        
        try:
            import psutil
            import netifaces

            ip = str()
            submask = str()
            gateway = str()

            flag_find = False
            
            # 获取IP和子网掩码
            for iface, addrs in psutil.net_if_addrs().items():
                if iface == interface_name:
                    for addr in addrs:
                        if addr.family == socket.AF_INET:
                            flag_find = True
                            ip = addr.address
                            submask = addr.netmask
                    break
            if flag_find == False:
                return False

            # 获取网关
            gws = netifaces.gateways()
            if 'default' in gws and netifaces.AF_INET in gws['default']:
                gateway = gws['default'][netifaces.AF_INET][0]
            return True, ip, submask, gateway
        except ImportError:
            return False
        except Exception as e:
            return False

    @staticmethod
    def get_default_interface():
        """获取默认网络接口名称"""
        try:
            import psutil
            for iface, addrs in psutil.net_if_addrs().items():
                for addr in addrs:
                    if addr.family == socket.AF_INET and not addr.address.startswith('127.'):
                        return iface
        except Exception:
            pass
        
        # 如果无法确定，返回空字符串
        return ""

    @staticmethod
    def generate_serial(prefix : str = 'SN', length : int = 10):
        """生成唯一序列号"""
        return f"{prefix}{uuid.uuid4().hex[:length].upper()}"

if __name__ == '__main__':
    print(NetUtil.subnet_to_cidr('255.255.255.0'))

    print(NetUtil.set_static_ip('eth0', '192.168.1.100', '255.255.255.0', '192.168.1.1'))

    print(NetUtil.get_network_interfaces())

    # print(NetUtil.get_network_info_ipv4('以太网'))
    print(NetUtil.get_network_info_ipv4('eth0'))

    # print(NetUtil.get_default_interface())

    # print(NetUtil.generate_serial())
